package com.grm.distributed.lock.service;

import com.grm.distributed.lock.common.Result;
import com.grm.distributed.lock.mapper.ProductMapper;
import com.grm.distributed.lock.pojo.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
// 多例模式，开启CGLIB代理，JDK代理是接口，ProductService是类，不合适
// @Scope(value = "prototype",proxyMode = ScopedProxyMode.TARGET_CLASS)
public class ProductService1 {
    @Autowired
    private ProductMapper productMapper;

    // ReentrantLock lock = new ReentrantLock();

    /*
        1. 不加锁，高并发会出问题
        2. 加锁，两种方式：(1) synchronized (2) ReentrantLock
              (1) 多例模式下会出问题 - @Scope(value = "prototype",proxyMode = ScopedProxyMode.TARGET_CLASS)
              (2) 事务模式下会出问题 - @Transactional(isolation = Isolation.READ_UNCOMMITTED)
              (3) 集群部署会出问题 - nginx负载均衡
     */
    // @Transactional(isolation = Isolation.READ_UNCOMMITTED)
    // @Transactional
    public synchronized Result sell() {
//        Product product = productMapper.queryById(1L);
//        if (product.getCount() > 0) {
//            product.setCount(product.getCount() - 1);
//            log.info("product current count = {}", product.getCount());
//            productMapper.update(product);
//        }

        // 利用update自带加锁功能，悲观锁
        // update product set count = count - 1 where id = #{id} and count > 0
        productMapper.sell(1L);
        Product product = productMapper.queryById(1L);
        log.info("product current count = {}", product.getCount());
        return Result.success(product.getCount());
    }
}
